#version 330 core

out vec4 FragColor;

uniform vec3 objectColor;
uniform vec3 viewPos;

in vec3 Normal;
in vec3 FragPos; // 空间坐标

struct Material {
    //    vec3 ambient;
    sampler2D diffuse;
    sampler2D specular;
    float shininess; //反光度 影响镜面高光的散射/半径
};

struct Light {
    vec3 position;
    vec3 direction;
    float cutOff; //切光角 内圈
    float outerCutOff; // 外圈

    vec3 ambient;
    vec3 diffuse;
    vec3 specular;

    float constant;
    float linear;
    float quadratic;
};

uniform Light light;
uniform Material material;

in vec2 TexCoords;

void main()
{
    vec3 ambient = light.ambient * vec3(texture2D(material.diffuse, TexCoords)) ;

    vec3 norm = normalize(Normal);
    vec3 lightDir = normalize(light.position - FragPos);

    float diff = max(dot(norm, lightDir), 0.0); //点乘得到漫反射角度
    vec3 diffuse = light.diffuse * (diff * vec3(texture2D(material.diffuse, TexCoords)));

    vec3 viewDir = normalize(viewPos - FragPos);
    vec3 reflectDir = reflect(-lightDir, norm);

    float spec = pow(max(dot(viewDir, reflectDir), 0.0), material.shininess);
    vec3 specular = light.specular * (vec3(texture2D(material.specular, TexCoords)) * spec);

    //衰减
    float distance    = length(light.position - FragPos);
    float attenuation = 1.0 / (light.constant + light.linear * distance +
                               light.quadratic * (distance * distance));

    // spotlight (soft edges)
    float theta = dot(lightDir, normalize(-light.direction));
    float epsilon = (light.cutOff - light.outerCutOff);
    float inensity = clamp((theta - light.outerCutOff) / epsilon, 0.0, 1.0);

    diffuse  *= inensity;
    specular *= inensity;

//    ambient  *= attenuation;
//    diffuse  *= attenuation;
//    specular *= attenuation;

    vec3 result = (ambient + diffuse + specular);
    FragColor = vec4(result, 1.0);
}
